import { ref } from "vue";
import { defineStore } from "pinia";
import { Season } from "@/type/game";
import { RainEffect } from "@/effects/RainEffect";
import { useTimeStore } from "@/store/timeStore";
import { SceneType } from "./sceneStore";

// 天气类型
export enum WeatherType {
  CLEAR = "sunny", // 晴天
  RAIN = "rain", // 雨天
  THUNDERSTORM = "lightning", // 暴风雨
}

// 天气强度范围
export interface WeatherIntensity {
  min: number;
  max: number;
  default: number;
}

// 天气强度配置
const WEATHER_INTENSITY: Record<WeatherType, WeatherIntensity> = {
  [WeatherType.CLEAR]: { min: 0, max: 0, default: 0 },
  [WeatherType.RAIN]: { min: 0, max: 2, default: 1 },
  [WeatherType.THUNDERSTORM]: { min: 1, max: 3, default: 2 },
};

// 天气周期配置
interface WeatherRule {
  season: Season;
  weatherPattern: {
    [day: number]: {
      type: WeatherType; // 天气类型
      intensity?: number; // 天气强度
      duration?: number; // 持续天数
    };
  };
}

// 固定天气规则
const WEATHER_RULES: WeatherRule[] = [
  {
    season: Season.SPRING,
    weatherPattern: {
      1: {
        // 第1-2天为晴天
        type: WeatherType.CLEAR,
        duration: 2,
      },
      3: {
        // 第3天为下雨
        type: WeatherType.RAIN,
        intensity: 1,
      },
      4: {
        // 第4-5天为晴天
        type: WeatherType.CLEAR,
        duration: 2,
      },
    },
  },
];

export const useWeatherStore = defineStore("weather", () => {
  const currentIntensity = ref<number>(0); // 当前天气强度
  let rainEffect: RainEffect | null = null; // 雨滴实例
  const currentWeather = ref<WeatherType>(WeatherType.CLEAR); // 当前天气类型
  const isWeatherActive = ref<boolean>(true); // 当前天气是否正在生效

  const initWeatherEffects = () => {
    rainEffect = new RainEffect();
  };

  /**
   * 设置天气
   * @param type 天气类型
   * @param intensity 天气强度
   */
  const setWeather = (type: WeatherType, intensity?: number) => {
    if (!rainEffect) {
      initWeatherEffects();
    }

    stopAllWeatherEffects();

    currentWeather.value = type;

    const intensityConfig = WEATHER_INTENSITY[type];
    const newIntensity =
      intensity !== undefined
        ? Math.max(
            intensityConfig.min,
            Math.min(intensityConfig.max, intensity)
          )
        : intensityConfig.default;
    currentIntensity.value = newIntensity;

    if (isWeatherActive.value) {
      startWeatherEffect(type, newIntensity);
    }
  };

  // 停止所有天气效果
  const stopAllWeatherEffects = () => {
    if (rainEffect) {
      rainEffect.stopRain();
    }
  };

  /**
   * 启动特定的天气效果
   * @param type 天气类型
   * @param intensity 天气强度
   */
  const startWeatherEffect = (type: WeatherType, intensity: number) => {
    currentWeather.value = type;
    switch (type) {
      case WeatherType.RAIN:
        if (rainEffect) {
          rainEffect.startRain(intensity);
        }
        break;
      default:
        break;
    }
  };

  /**
   * 根据场景类型控制天气效果
   * @param sceneType 场景类型
   */
  const updateWeatherForScene = (sceneType: SceneType) => {
    if (sceneType === SceneType.HOUSE) {
      isWeatherActive.value = false;
      stopAllWeatherEffects();
      if (rainEffect) {
        rainEffect.hideRainEffect(); // 需要在RainEffect类中添加此方法
      }
    }

    // 室外天气
    else if (sceneType === SceneType.FARM) {
      isWeatherActive.value = true;
      if (currentWeather.value === WeatherType.RAIN) {
        if (rainEffect) {
          rainEffect.showRainEffect();
        } else {
          startWeatherEffect(currentWeather.value, currentIntensity.value);
        }
      }
    }
  };

  // 随机生成天气
  const generateRandomWeather = (day: number): WeatherType => {
    if (day >= 6) {
      const rand = Math.random();
      if (rand < 0.6) {
        return WeatherType.CLEAR;
      }
      if (rand < 0.9) {
        return WeatherType.RAIN;
      }
      return WeatherType.THUNDERSTORM;
    }
    return WeatherType.CLEAR;
  };

  const timeStore = useTimeStore();
  let lastCheckedDay = timeStore.gameTime.day;

  // 检查天气规则，自动更新天气
  const checkWeatherRules = () => {
    const currentDay = timeStore.gameTime.day;
    const currentSeason = timeStore.gameTime.season;

    const rule = WEATHER_RULES.find((r) => r.season === currentSeason);
    if (rule) {
      for (const [startDay, config] of Object.entries(rule.weatherPattern)) {
        const dayNum = parseInt(startDay);
        if (
          currentDay >= dayNum &&
          currentDay < dayNum + (config.duration || 1)
        ) {
          setWeather(config.type, config.intensity);
          return;
        }
      }
    }
    setWeather(generateRandomWeather(currentDay));
  };

  timeStore.$subscribe((mutation, state) => {
    // 只有当天数变化时才检查天气规则
    if (state.gameTime.day !== lastCheckedDay) {
      lastCheckedDay = state.gameTime.day;
      if (rainEffect) {
        rainEffect.clear();
        checkWeatherRules();
      }
    }
  });

  return {
    currentWeather,
    currentIntensity,
    setWeather,
    initWeatherEffects,
    stopAllWeatherEffects,
    generateRandomWeather,
    checkWeatherRules,
    updateWeatherForScene,
    startWeatherEffect,
  };
});
